package com.glodon.paas.document.service.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ws.rs.core.MediaType;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.glodon.paas.account.api.bean.AccountConstant;
import com.glodon.paas.account.api.bean.Communicate;
import com.glodon.paas.account.api.bean.Org;
import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.consts.StringConst;
import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.document.api.bean.FileQuery;
import com.glodon.paas.document.dao.domain.FileInfoEntity;
import com.glodon.paas.document.dao.domain.RevisionEntity;
import com.glodon.paas.document.service.FileService;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.util.BeanFactoryUtil;
import com.glodon.paas.util.HttpUtils;
import com.glodon.paas.util.StringUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

@Component
public class WebService {

    private static final Logger       LOGGER = LoggerFactory.getLogger(WebService.class);

    private static final ClientConfig clientConfig;

    static {
        clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    }

    public User getUser(String value) {
        if (StringUtils.isBlank(value)) {
            PaasServerExceptionFactory.validateException("can not get user by value[" + value + "]", null);
        }
        StringBuffer uri = new StringBuffer(DocumentConfig.API_INTERNAL_ACCOUNT_URL + "/user/" + value + "?");
        if (StringUtil.isEmail(value) || StringUtil.isMobile(value)) {
            uri.append("account");
        } else {
            uri.append("id");
        }

        return getUserFromAccount(value, uri.toString());
    }

    public User getInactiveUser(String value) {
        if (StringUtils.isBlank(value)) {
            PaasServerExceptionFactory.validateException("can not get user by value[" + value + "]", null);
        }
        StringBuffer uri = new StringBuffer(DocumentConfig.API_INTERNAL_ACCOUNT_URL + "/user/" + value + "?");
        if (StringUtil.isEmail(value) || StringUtil.isMobile(value)) {
            uri.append("account");
        } else {
            uri.append("id");
        }
        uri.append("&status=" + AccountConstant.USER_STATUS_INACTIVE);
        return getUserFromAccount(value, uri.toString());

    }

    private User getUserFromAccount(String value, String url) {
        LOGGER.info("Internal API Call [GET]:" + url);
        WebResource resource = Client.create(clientConfig).resource(url);
        ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
        if (c.getStatus() == 204) {
            return null;
        } else if (c.getStatus() != 200) {
            throw PaasServerExceptionFactory.internalAPIException("get users by email, internal API exception. "
                                                                          + c.getEntity(String.class), null);
        }
        User[] users = c.getEntity(User[].class);
        if (users.length > 1) {
            LOGGER.warn("find too many users by value:[" + value + "]");
            return users[0];
        } else if (users.length == 1) {
            return users[0];
        } else {
            return null;
        }
    }
    public List<User> getUserByIds(Set<String> ids,boolean isEmail) {
        if (ids == null) {
            PaasServerExceptionFactory.validateException("can not get users by value[" + ids + "]", null);
        }
        List<User> ret = new ArrayList<User>();
        StringBuffer idstr = new StringBuffer();
        int size = ids.size();
        int count = 0;
        for (String id : ids) {
            idstr.append(id + ",");
            count++;
            if (count % 20 == 0 || count == size) {
                if (idstr.toString().endsWith(",")) {
                    idstr.deleteCharAt(idstr.length() - 1);
                }
                WebResource resource =null;
                if(isEmail){
                    resource = Client.create(clientConfig).resource(DocumentConfig.API_INTERNAL_ACCOUNT_URL
                                                                                + "/user/" + idstr + "?account");
                }else{
                    resource = Client.create(clientConfig).resource(DocumentConfig.API_INTERNAL_ACCOUNT_URL
                                                                                + "/user/" + idstr + "?id");
                }
                
                ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
                if (c.getStatus() != 200) {
                    throw PaasServerExceptionFactory.internalAPIException("get users by ids internal API exception. "
                                                                          + c.getEntity(String.class), null);
                }
                idstr.setLength(0);
                User[] tempUsers = c.getEntity(User[].class);
                if (tempUsers != null) {
                    ret.addAll(Arrays.asList(tempUsers));
                }
            }
        }

        return ret;
    }
    public List<User> getUserByIds(Set<String> ids) {
       return getUserByIds(ids,false);
    }

    public User createInactiveUser(String emailMobile) {
        if (StringUtils.isBlank(emailMobile)) {
            PaasServerExceptionFactory.validateException("can not create user by value[" + emailMobile + "]", null);
        }
        StringBuffer uri = new StringBuffer(DocumentConfig.API_INTERNAL_ACCOUNT_URL + "/user/" + emailMobile + "?");
        if (StringUtil.isEmail(emailMobile)) {
            uri.append("email");
        } else if (StringUtil.isMobile(emailMobile)) {
            uri.append("mobile");
        } else {
            PaasServerExceptionFactory.validateException("create inactive user fail, Email/Mobile is empty", null);
        }

        LOGGER.info("Internal API Call [POST]:" + uri.toString());
        WebResource resource = Client.create(clientConfig).resource(uri.toString());
        ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class);
        if (c.getStatus() != 200) {
            throw PaasServerExceptionFactory.internalAPIException("create inactive user, internal API exception. "
                                                                          + c.getEntity(String.class), null);
        }
        return c.getEntity(User.class);
    }

    public String addCommunicate(String userId, String contactId, String remarkName) {
        String url = "/communicateBook/userId/" + userId + "/contactId/" + contactId + "/remarkName/" + HttpUtils.encodeUTF8(remarkName);
        LOGGER.info("Internal API Call [POST]:" + DocumentConfig.API_INTERNAL_ACCOUNT_URL + url);
        WebResource resource = Client.create().resource(DocumentConfig.API_INTERNAL_ACCOUNT_URL + url);
        ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class);
        if (c.getStatus() != 200) {
            throw PaasServerExceptionFactory.internalAPIException("addRelation, internal API exception. "
                                                                          + c.getEntity(String.class), null);
        }
        return c.getEntity(String.class);
    }

    public Communicate queryCommunicateByContactId(String userId, String contactId) {
        // /communicateBook/userId/{userId}/contactId/{contactId}
        String url = "/communicateBook/userId/" + userId + "/contactId/" + contactId;
        LOGGER.info("Internal API Call [GET]:" + DocumentConfig.API_INTERNAL_ACCOUNT_URL + url);
        WebResource resource = Client.create(clientConfig).resource(DocumentConfig.API_INTERNAL_ACCOUNT_URL + url);
        ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
        if (c.getStatus() == 204) {
            return null;
        }
        if (c.getStatus() != 200) {
            throw PaasServerExceptionFactory.internalAPIException("queryCommunicateByContactId, internal API exception. "
                                                                          + c.getEntity(String.class), null);
        }
        return c.getEntity(Communicate.class);
    }
    
    public List<Communicate> getContactList(String userId){
        String url =  "/communicateBook/userId/" + userId;
        WebResource resource = Client.create(clientConfig).resource(DocumentConfig.API_INTERNAL_ACCOUNT_URL + url);
        ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
        if (c.getStatus() == 204) {
            return null;
        }
        if (c.getStatus() != 200) {
            throw PaasServerExceptionFactory.internalAPIException("queryCommunicateByContactId, internal API exception. "
                                                                          + c.getEntity(String.class), null);
        }
        String str = c.getEntity(String.class);
        ObjectMapper mapper = new ObjectMapper();
        List<Communicate> result = new ArrayList<Communicate>() ;
        try {
            result = mapper.readValue(str, new TypeReference<List<Communicate>>(){   });
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result;
    }
    
    public String createDataBag(FileInfoEntity file, RevisionEntity revision, String publicToken) {
        String[] extensions = DocumentConfig.CREATE_DATABAG_FILE_TYPE.split(StringConst.SEPARATOR_COMMA);
        for (String extension : extensions) {
            if (extension.equalsIgnoreCase(file.getExtension())) {
                String inputURL;
                if ("dwg".equalsIgnoreCase(file.getExtension())) {
                    FileService fileService = (FileService) BeanFactoryUtil.getBean("fileService");
                    inputURL = DocumentConfig.API_INTERNAL_DOCUMENT_URL + "/file/userId/" + file.getUpdator()
                               + fileService.getPath(file.getUpdator(), file.getId(), true) + "?rev="
                               + revision.getRevisionNumber();
                } else {
                    inputURL = DocumentConfig.API_INTERNAL_DOCUMENT_URL + "/file/" + file.getId() + "?type=id&rev="
                               + revision.getRevisionNumber();
                }
                DataBagParam param = new DataBagParam(file.getUpdator(), inputURL, file.getId(), file.getName(),
                                                      file.getExtension());
                param.setToken(publicToken);
                try {
                    LOGGER.info("start create databag:" + DocumentConfig.API_INTERNAL_DATABAG_URL + "/" + extension);
                    LOGGER.info("input:" + param.getInput());
                    WebResource resource = Client.create(clientConfig).resource(DocumentConfig.API_INTERNAL_DATABAG_URL
                                                                                        + "/" + extension);
                    ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, param);
                    if (c.getStatus() != 200) {
                        throw PaasServerExceptionFactory.internalAPIException("create databag fail, internal API exception. "
                                                                                      + c.getEntity(String.class), null);
                    }
                    DataBagResult result = c.getEntity(DataBagResult.class);
                    if (result != null && StringUtils.isNotEmpty(result.getDatabagId())) {
                        LOGGER.info("end create databag for Revision[" + result.getDatabagId() + "], success.");
                    } else {
                        LOGGER.info("end create databag for Revision[" + result.getDatabagId() + "], fail.");
                    }
                    return result.getDatabagId();
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    public void deleteDataBag(String databagId, String alternateDatabagId) {
        if(StringUtils.isBlank(databagId)){
            return;
        }
        try {
            StringBuilder url = new StringBuilder(DocumentConfig.API_INTERNAL_DATABAG_URL + "/" + databagId);
            if (StringUtils.isNotBlank(alternateDatabagId) && !databagId.equals(alternateDatabagId)) {
                url.append("?alternatePublic=" + alternateDatabagId);
            }
            LOGGER.debug("delete databag, URL: "+url.toString());
            WebResource resource = Client.create().resource(url.toString());
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).delete(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("delete databag failed.databagid:" + databagId);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 查询数据包的创建进度.
     * 
     * @param databagId
     * @return
     */
    public String queryDatabagProgress(String databagId) {
        String result = "-1";// 默认-1为失败
        try {
            WebResource resource = Client.create().resource(
                    DocumentConfig.API_INTERNAL_DATABAG_URL + "/" + databagId + "/progress");
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
            String progress = c.getEntity(String.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("query databag progress failed. databagid: {}, reponse:{}", databagId, progress);
            } else {
                result = progress;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result;// -1约定代表失败
    }

    public User addProjectRole(String loginId, String userId, String projectId, String roleId,String orgId) {
        User usr = null;
        try {
            WebResource resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/project/" + userId
                                                                    + "/" + projectId + "/" + roleId+"/"+orgId);
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",
                                                                                                                             loginId).post(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("insert member failed. UserId:" + userId + ",project:" + projectId + ",role:" + roleId);
            }
            String user = c.getEntity(String.class);
            ObjectMapper mapper = new ObjectMapper();
            Map<String, User> map = mapper.readValue(user, new TypeReference<Map<String, User>>() {
            });
            usr = map.get("user");
            if (usr == null) {
                LOGGER.warn("User is not exist.");
                throw PaasServerExceptionFactory.internalAPIException("Add member into account failed.",
                                                                      new Exception("User is not exist."));

            }
            // 更新本地缓存的user
            UserProvider userProvider = (UserProvider) BeanFactoryUtil.getBean("userProvider");
            if (userProvider != null && userProvider.currentUser() != null) {
                userProvider.currentUser().setProjects(this.getUser(userId).getProjects());
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return usr;
    }

    public boolean deleteProjectRole(String loginId, String userId, String projectId, String roleId,String orgId) {
        int result = 0;
        try {
            WebResource resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/project/"
                                                                    + String.valueOf(userId) + "/"
                                                                    + String.valueOf(projectId) + "/"
                                                                    + String.valueOf(roleId)+"/"+orgId);
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",
                                                                                                                             loginId).delete(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("Delete failed. UserId:" + userId + ",project:" + projectId + ",role:" + roleId);
            }
            String user = c.getEntity(String.class);
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Integer> map = mapper.readValue(user, new TypeReference<Map<String, Integer>>() {
            });
            result = map.get("result");
            if (result == 0) {
                LOGGER.warn("Delete nothing.");
                throw PaasServerExceptionFactory.internalAPIException("Nothing is deleted.",
                                                                      new Exception("Nothing is deleted."));
            }
            // 更新本地缓存的user
            UserProvider userProvider = (UserProvider) BeanFactoryUtil.getBean("userProvider");
            if (userProvider != null && userProvider.currentUser() != null) {
                userProvider.currentUser().setProjects(this.getUser(loginId).getProjects());
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result > 0;
    }

    public boolean updateProjectRole(String userId, String projectId, String roleId, String newRoleId) {
        int result = 0;
        try {
            WebResource resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/project/"
                                                                    + String.valueOf(projectId) + "/"
                                                                    + String.valueOf(roleId) + "/update/"
                                                                    + String.valueOf(newRoleId));
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",
                                                                                                                             userId).post(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("Update failed. project:" + projectId + ",role:" + roleId + ",new role:" + newRoleId);
            }
            String str = c.getEntity(String.class);
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Integer> map = mapper.readValue(str, new TypeReference<Map<String, Integer>>() {
            });
            result = map.get("result");
            // 更新本地缓存的user
            UserProvider userProvider = (UserProvider) BeanFactoryUtil.getBean("userProvider");
            if (userProvider != null && userProvider.currentUser() != null) {
                userProvider.currentUser().setProjects(this.getUser(userId).getProjects());
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result >= 0;
    }

//    public Org getOrgById(String orgId, String userId) {
//        Org org = null;
//        try {
//            WebResource resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/org/" + orgId);
//            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",
//                                                                                                                             userId).get(ClientResponse.class);
//            if (c.getStatus() != 200) {
//                LOGGER.warn("Get organization failed. Organization:" + orgId);
//            }
//            String str = c.getEntity(String.class);
//            ObjectMapper mapper = new ObjectMapper();
//            Map<String, Org> map = mapper.readValue(str, new TypeReference<Map<String, Org>>() {
//            });
//            org = map.get("org");
//            if (org == null) {
//                LOGGER.warn("organization is not exist.");
//                throw PaasServerExceptionFactory.internalAPIException("organization is not exist.",
//                                                                      new Exception("organization is not exist.."));
//
//            }
//
//        } catch (Exception e) {
//            LOGGER.error(e.getMessage(), e);
//        }
//        return org;
//    }
    public Org getOrgById(String orgId, String userId,boolean hasMembers) {
        Org org = null;
        try {
            WebResource resource = null;
            if(hasMembers){
                resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/org/" + orgId+"/member");
            }else{
                resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/org/" + orgId);
            }
            
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",
                                                                                                                             userId).get(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("Get organization failed. Organization:" + orgId);
            }
            String str = c.getEntity(String.class);
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Org> map = mapper.readValue(str, new TypeReference<Map<String, Org>>() {
            });
            org = map.get("org");
            if (org == null) {
                LOGGER.warn("organization is not exist.");
                throw PaasServerExceptionFactory.internalAPIException("organization is not exist.",
                                                                      new Exception("organization is not exist.."));

            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return org;
    }
    public Map<String, Object> getOrg(String userId) {
        Map<String, Object> map = null;
        try {
            WebResource resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/org");
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",
                                                                                                                             userId).get(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("Get organization failed.");
            }
            String str = c.getEntity(String.class);
            ObjectMapper mapper = new ObjectMapper();
            map = mapper.readValue(str, new TypeReference<Map<String, Object>>() {
            });
            if (map == null) {
                LOGGER.warn("organization is not exist.");
                throw PaasServerExceptionFactory.internalAPIException("organization is not exist.",
                                                                      new Exception("organization is not exist.."));

            }
            
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return map;
    }
    public List<Org> getInstitution(String userId) {
        List<Org> orgList = new ArrayList<Org>();
        try {
            WebResource resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/institution");
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",userId).get(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("Get organization failed." );
            }
            String str = c.getEntity(String.class);
            ObjectMapper mapper = new ObjectMapper();
            Map<String, List<Org>> map = mapper.readValue(str, new TypeReference<Map<String,  List<Org>>>() {
            });
            orgList = map.get("org");
            if (orgList.isEmpty()){
                LOGGER.warn("organization is not exist.");
                throw PaasServerExceptionFactory.internalAPIException("organization is not exist.",
                                                                      new Exception("organization is not exist.."));

            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return orgList;
    }
    public Org getOrgPath(String orgId,String userId) {
        Org org = null;
        try {
            WebResource resource = Client.create().resource(DocumentConfig.ACCOUNT_SERVER_URL + "/org/"+orgId+"/path");
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("INTERNAL_LOGIN_USER",userId).get(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("Get organization failed." );
            }
            String str = c.getEntity(String.class);
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Org> map = mapper.readValue(str, new TypeReference<Map<String, Org>>() {
            });
            org = map.get("org");
            if (org == null) {
                LOGGER.warn("organization is not exist.");
                throw PaasServerExceptionFactory.internalAPIException("organization is not exist.",
                                                                      new Exception("organization is not exist.."));

            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return org;
    }
    
    public String publicDataBag(String databagId) {
        try {
            WebResource resource = Client.create().resource(DocumentConfig.API_INTERNAL_DATABAG_URL + "/public/" + databagId);
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("public databag failed.databagid:" + databagId);
            } else {
                return c.getEntity(String.class);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    public void cancelPublicDataBag(String databagId) {
        try {
            WebResource resource = Client.create().resource(DocumentConfig.API_INTERNAL_DATABAG_URL + "/public/"
                                                                    + databagId);
            ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).delete(ClientResponse.class);
            if (c.getStatus() != 200) {
                LOGGER.warn("cancel public databag failed.databagid:" + databagId);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    /**
     * 通知search有关document的变更事件
     * 
     * @param fileId
     * @param event
     *            这里可以是"upload", "delete", "rename"和"move"
     */
    public static void notifySearch(File file, String event) {
        try {
            if(StringUtils.isBlank(DocumentConfig.API_INTERNAL_SEARCH_URL)){
                LOGGER.warn("notify Search failed, Server URL is empty");
                return;
            }
            String url = DocumentConfig.API_INTERNAL_SEARCH_URL + "/file/" + file.getId() + "?userId=" + file.getOwnerId() + "&event=" + event;
            WebResource resource = Client.create().resource(url);
            ClientResponse resp = resource.type(MediaType.APPLICATION_JSON_TYPE).put(ClientResponse.class);
            if (resp.getStatus() != 200) {
                LOGGER.warn("failed to notify search server with file:" + file.getId() + " and event:" + event);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 向search发送搜索请求.
     * 
     * @param query
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<File> doSearch(FileQuery query) {
        List<File> files = new ArrayList<File>();
        String url = DocumentConfig.API_INTERNAL_SEARCH_URL + "/file";
        WebResource resource = Client.create(clientConfig).resource(url);
        Map bean = null;
        try {
            bean = PropertyUtils.describe(query);
            bean.remove("class");// PropertyUtils工具自动加上的
            Iterator iterator = bean.keySet().iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                Object value = bean.get(key);
                if (value != null) {
                    resource = resource.queryParam(key, value.toString());
                }
            }
        } catch (Exception e) {
            throw PaasServerExceptionFactory.systemException("FileQuery isn't regular Bean.", e);
        }
        ClientResponse resp = resource.type(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
        if (resp.getStatus() != 200) {
            LOGGER.warn("failed to search for:" + resp.getEntity(String.class));
        } else {
            GenericType<List<File>> genericType = new GenericType<List<File>>() {
            };
            files = resp.getEntity(genericType);
        }
        return files;
    }


}
